package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.api.db.UserApi;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.FriendApi;
import com.tanhua.api.mongo.RecommendUserApi;
import com.tanhua.api.mongo.UserLikeApi;
import com.tanhua.api.mongo.VisitorsApi;
import com.tanhua.db.User;
import com.tanhua.db.UserInfo;
import com.tanhua.mongo.Friend;
import com.tanhua.mongo.UserLike;
import com.tanhua.mongo.Visitors;
import com.tanhua.template.AipFaceTemplate;
import com.tanhua.template.HuanXinTemplate;
import com.tanhua.template.OssTemplate;
import com.tanhua.template.SmsTemplate;
import com.tanhua.uti.JwtUtil;
import com.tanhua.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Reference
    private UserApi userApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private FriendApi friendApi;
    @Reference
    private VisitorsApi visitorsApi;

    @Reference
    private UserLikeApi userLikeApi;
    @Autowired
    private SmsTemplate smsTemplate;
    @Reference
    private RecommendUserApi recommendUserApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public ResponseEntity saveUser(@RequestBody User user) {
        Long id = userApi.saveUser(user);
        return ResponseEntity.ok(id);
    }


    public ResponseEntity findByPhone(String phone) {
        User user = userApi.findByPhone(phone);
        return ResponseEntity.ok(user);
    }


    public ResponseEntity login(String phone) {

        // 2 获取随机6位数
        String code = "123456";
        //String code = RandomUtil.randomNumbers(6);
        // 3 调用阿里云工具类抽成的启动器模板
        System.out.println(phone);
        System.out.println(code);
        //验证码写死
        //smsTemplate.sendSms(phone,code);
        //4  放入redis中（设置过期时间）
        stringRedisTemplate.opsForValue().set("SMS_CODE_" + phone, code, 10, TimeUnit.MINUTES);
        //扩展取：String value=stringRedisTemplate.opsForValue().get("key");
        //5 返回值
        return ResponseEntity.ok(null);

    }

    public ResponseEntity loginVerification(String phone, String vCode) {
        String redisCode = stringRedisTemplate.opsForValue().get("SMS_CODE_" + phone);
        if (!StringUtils.equals(vCode, redisCode)) {
            return ResponseEntity.status(500).body("验证码错误");
        }

        //优化验证码：用完即删
        //stringRedisTemplate.delete("SMS_CODE_" + phone);

        //4 一致--带着手机号去查询
        User user = userApi.findByPhone(phone);
        Boolean flag = false;

        if (user == null) {
            user = new User();
            user.setPhone(phone);
            Long id = userApi.saveUser(user);
            user.setId(id);
            flag = true;
            huanXinTemplate.register(id);

        }
        //记录用户的当前行为
        //告诉后台tb_log形成一条用户的操作数据

        Map map = new HashMap<>();
        map.put("userId", user.getId());
        map.put("type", flag ? "0102" : "0101");
        rocketMQTemplate.convertAndSend("tanhua-log", map);
        //将当前用户加密成一串字符串token
        String token = JwtUtil.createToken(user.getPhone(), "tanhua");
        //当前用户对象转换成json
        String userJson = JSON.toJSONString(user);
        //将token放入redis中
        stringRedisTemplate.opsForValue().set("TOKEN_" + token, userJson, 1, TimeUnit.DAYS);
        //返回json
        Map jsonMap = new HashMap<String, Object>();
        jsonMap.put("token", token);
        jsonMap.put("isNew", flag);
        System.out.println(jsonMap);
        return ResponseEntity.ok(jsonMap);
    }

    public void loginReginfo(UserInfo userInfo, String token) {
        User user = findUserByToken(token);
        userInfo.setId(user.getId());
        userApi.save(userInfo);

    }

    public User findUserByToken(String token) {
        String json = stringRedisTemplate.opsForValue().get("TOKEN_" + token);
        User user = JSON.parseObject(json, User.class);
        return user;
    }

    public ResponseEntity loginReginfoPic(MultipartFile headPhoto, String token) throws IOException {

        //根据token获取用户对象
        User user = findUserByToken(token);
        //人脸识别
        boolean detect = aipFaceTemplate.detect(headPhoto.getBytes());
        if (detect == false) { // 检测失败
            return ResponseEntity.status(500).body("人脸识别错误");
        }
        String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //更新userInfo
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setAvatar(url);//touxiang
        userInfo.setCoverPic(url);//fengmian

        userInfoApi.update(userInfo);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity findUserInfoVo(Long userID) {
        UserInfo userInfo = userInfoApi.findByUserId(userID);
        UserInfoVo userInfoVo = new UserInfoVo();
        //copyProperties把userInfo复制到userInfoVo
        BeanUtils.copyProperties(userInfo, userInfoVo);

        //注意返回的是userInfoVo不是userInfo
        return ResponseEntity.ok(userInfoVo);
    }

    public ResponseEntity updateUserInfo(UserInfo userInfo, String token) {
        User user = findUserByToken(token);
        userInfo.setId(user.getId());
        userInfoApi.update(userInfo);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity counts() {
        //相互喜欢数量
        Integer friendCount = friendApi.count(UserHolder.getUser().getId());
        //我喜欢的数量
        Integer loveCount = userLikeApi.findLoveCount(UserHolder.getUser().getId());
        //喜欢我的数量
        Integer fanCount = userLikeApi.findFanCount(UserHolder.getUser().getId());
        CountsVo countsVo = new CountsVo(friendCount, loveCount, fanCount);
        return ResponseEntity.ok(countsVo);
    }

    public ResponseEntity findMyCountList(Integer type, Integer pageNum, Integer pageSize) {
        List<UserLikeListVo> userLikeVoList = new ArrayList<>();
        Long userId = UserHolder.getUser().getId();//当前用户id
        PageBeanVo pageBeanVo = null;
        switch (type) {
            case 1: {
                pageBeanVo = friendApi.contactsListByUserId(pageNum, pageSize, userId);
                List<Friend> friendList = (List<Friend>) pageBeanVo.getItems();
                if (CollectionUtil.isNotEmpty(friendList)) {
                    for (Friend friend : friendList) {
                        UserInfo userInfo = userInfoApi.findByUserId(friend.getFriendId());
                        UserLikeListVo userLikeListVo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo, userLikeListVo);
                        Long score = recommendUserApi.findScore(friend.getFriendId(), friend.getUserId());
                        userLikeListVo.setMatchRate(Math.toIntExact(score));
                        userLikeVoList.add(userLikeListVo);
                    }

                }
                break;
            }
            case 2: {
                pageBeanVo = userLikeApi.findLoveList(pageNum, pageSize, userId);
                List<UserLike> userLikeList = (List<UserLike>) pageBeanVo.getItems();
                if (CollectionUtil.isNotEmpty(userLikeList)) {
                    for (UserLike userLike : userLikeList) {
                        UserInfo userInfo = userInfoApi.findByUserId(userLike.getLikeUserId());
                        UserLikeListVo userLikeListVo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo, userLikeListVo);
                        Long score = recommendUserApi.findScore(userLike.getUserId(), userLike.getLikeUserId());
                        userLikeListVo.setMatchRate(Math.toIntExact(score));
                        userLikeVoList.add(userLikeListVo);
                    }
                }
                break;
            }
            case 3: {
                pageBeanVo = userLikeApi.findFanList(pageNum, pageSize, userId);
                List<UserLike> userLikeList = (List<UserLike>) pageBeanVo.getItems();
                if (CollectionUtil.isNotEmpty(userLikeList)) {
                    for (UserLike userLike : userLikeList) {
                        UserInfo userInfo = userInfoApi.findByUserId(userLike.getUserId());
                        UserLikeListVo userLikeListVo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo, userLikeListVo);
                        Long score = recommendUserApi.findScore(userLike.getUserId(), userLike.getLikeUserId());
                        userLikeListVo.setMatchRate(Math.toIntExact(score));
                        userLikeVoList.add(userLikeListVo);
                    }

                }
                break;
            }
            case 4: {
                pageBeanVo = visitorsApi.findHistoryList(pageNum, pageSize, userId);
                List<Visitors> visitorsList = (List<Visitors>) pageBeanVo.getItems();
                if (CollectionUtil.isNotEmpty(visitorsList)) {
                    for (Visitors visitors : visitorsList) {
                        UserInfo userInfo = userInfoApi.findByUserId(visitors.getVisitorUserId());
                        System.out.println(visitors.getVisitorUserId());
                        UserLikeListVo userLikeListVo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo, userLikeListVo);
                        //缘分值
                        Long score = recommendUserApi.findScore(visitors.getVisitorUserId(), UserHolder.getUser().getId());
                        userLikeListVo.setMatchRate(score.intValue());
                        userLikeVoList.add(userLikeListVo);
                        System.out.println(userLikeVoList);
                    }

                }
                break;
            }

        }
        pageBeanVo.setItems(userLikeVoList);
        return ResponseEntity.ok(pageBeanVo);

    }

    public ResponseEntity fansToFriend(Long fanId) {
        //删除粉丝
        userLikeApi.removeFans(fanId, UserHolder.getUser().getId());
        //插入朋友
        friendApi.save(UserHolder.getUser().getId(), fanId);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity removeLove(Long loveId) {
        // 1 判断用户点击的是哪个取消喜欢
        Boolean flag = friendApi.isFriend(UserHolder.getUser().getId(), loveId);
        if (flag) {
            // 2 互相喜欢的---删除好友表的2条数据 userLike添加一个粉丝数据
            friendApi.removeFriend(UserHolder.getUser().getId(), loveId);
            userLikeApi.addFans(UserHolder.getUser().getId(), loveId);
        } else {
            // 3 喜欢--直接删除喜欢的这个人
            userLikeApi.removeFans(UserHolder.getUser().getId(), loveId.longValue());
        }

        return ResponseEntity.ok(null);
    }

    public ResponseEntity checkVerificationCode(String verificationCode) {
        String phone = UserHolder.getUser().getPhone();
        String redisCode = stringRedisTemplate.opsForValue().get("SMS_CODE_" + phone);
        boolean verification = StringUtils.equals(verificationCode, redisCode);
        Map<String ,Boolean> map = new HashMap<>();
        map.put("verification",verification);
        return ResponseEntity.ok(map);
    }

    public ResponseEntity savePhone(String phone2) {

        String phone1 = UserHolder.getUser().getPhone();
        userApi.updateUser(phone1,phone2);
        return ResponseEntity.ok(null);
    }
}
